package com.wsz.security.config.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wsz.security.Exception.CodeMatchException;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class LoginKaptchaFilter extends UsernamePasswordAuthenticationFilter {

    public static final String CODE= "code";

    private String Code = "code";

    public String getCode() {
        return Code;
    }

    public void setCode(String code) {
        Code = code;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {


        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
            try {
                Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);

                String username = map.get(this.getUsernameParameter());
                String password = map.get(this.getPasswordParameter());
                String code = map.get(this.getCode());

                String sessionCode = (String) request.getSession().getAttribute("code");

                if(!StringUtils.isEmpty(code) && !StringUtils.isEmpty(sessionCode) && code.equals(sessionCode)){
                    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                    this.setDetails(request, authRequest);
                    return this.getAuthenticationManager().authenticate(authRequest);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        throw new CodeMatchException("验证码错误");
    }
}
